package net.chinatax.rz.zzs;

import java.io.File;
import java.io.IOException;
import java.io.Writer;
import java.util.ArrayList;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.log4j.Logger;
import org.json.simple.JSONArray;
import org.json.simple.JSONObject;
/**
 * 传入增值税专票认证数据，持久化到本地磁盘的INPUT文件夹
 * 读取OUTPUT文件夹，返回以前的认证结果
 * @author weitao
 */
public class ZzsRzOutSiteInvokeServlet extends HttpServlet {

	private Logger log = org.apache.log4j.Logger.getLogger(getClass());
	
    public void init()throws ServletException{
    	//nothing
    }

    /**
     * @deprecated
     * @param 
     */
    public void doPost(HttpServletRequest request, HttpServletResponse response)throws ServletException,IOException{
    	
         doGet(request,response);
    }
    
    /**
     * @param{
     * nsrsbh:**,
     * fpdm:**,
     * fphm:**,
     * kpyear:**,
     * kpmonth:**,
     * kpday:**,
     * gsbh:**,
     * action:**,
     * miwen1:**,
     * miwen2:**,
     * miwen3:**,
     * miwen4:**,
     * jine:**,
     * shuie:**,
     * xsbh:**,
     * fpid:**,
     * gd:**
     * }
     * @return json:{
     * 	state:1，有结果；0，无结果；-1，错误
     * 	data:[{fpdm:**,fphm:**,rzjg_dm:*,rzjg_mc:**},...]
     * }
     */
    public void doGet(HttpServletRequest request, HttpServletResponse response)throws ServletException,IOException{
    	Enumeration en = request.getParameterNames();

        while (en.hasMoreElements()) {

            String paramName = (String) en.nextElement();
            System.out.println(paramName + " = " + request.getParameter(paramName) + "<br/>");

        }
    	//校验配置是否完整
		if(Tools.pathMap.get(Tools.ZZSOUTPUT)==null||null==Tools.pathMap.get(Tools.ZZSINPUT))
		{
			log.error("属性配置不正确，输入或输出文件夹配置为空");
			return ;//TODO
		}
    	String fpdm = request.getParameter(Tools.FP.FPDM);//发票代码
    	String fphm = request.getParameter(Tools.FP.FPHM);//发票号码
    	String UUID = Tools.UID(fpdm+"_"+fphm);//发票信息本地存放文件名称
    	if(!new File(Tools.pathMap.get(Tools.ZZSINPUT).toString()).exists()){
			new File(Tools.pathMap.get(Tools.ZZSINPUT).toString()).mkdirs();
		}
    	String U_filePath = Tools.pathMap.get(Tools.ZZSINPUT).toString()+UUID + ".properties";
    	new File(U_filePath).createNewFile();
    	Map singleDRZFP = new HashMap();
    	singleDRZFP.put(Tools.FP.FPDM, fpdm);
    	singleDRZFP.put(Tools.FP.FPHM, fphm);
    	singleDRZFP.putAll(request.getParameterMap());
    	//TODO
    	singleDRZFP.put(Tools.FP.RZJG_DM, "");
    	singleDRZFP.put(Tools.FP.RZJG_MC, "");
    	
    	   	
    	Tools.writeAllProperties(U_filePath, singleDRZFP);
    	String result = getRzResult();
    	
        response.setContentType("text/html;charset=utf-8");
        Writer resout = response.getWriter();
        resout.write( "{\"state\":\"1\",data:{"+result+"}" );
        resout.flush();
        resout.close();
    }
    
    /**
     * 获取认证结果列表，封装成json格式，返回到客户端。
     * @return 认证结果json串
     */
    public String getRzResult(){
    	
		List list = new ArrayList();
		
		if(!new File(Tools.pathMap.get(Tools.ZZSOUTPUT).toString()).exists()){
			new File(Tools.pathMap.get(Tools.ZZSOUTPUT).toString()).mkdirs();
		}
		//获取结果列表
		File fileList[] = new File(Tools.pathMap.get(Tools.ZZSOUTPUT).toString()).listFiles();
		String[] filePaths = new String[fileList.length];
		for(int i = 0;i < fileList.length; i++){
			filePaths[i] = fileList[i].getAbsolutePath();
			list.add(this.getSingleResult(filePaths[i]));
			fileList[i].delete();//删除文件
		}
		
		
		JSONArray ja = new JSONArray();
		for(int i=0; i<list.size(); i++) {
			JSONObject jo = new JSONObject();
			jo.putAll((Map)list.get(i));
			ja.add(jo);
		}	
    	return ja.toJSONString();
    }
    
    //获取单条发票数据
    public Map getSingleResult(String fileName){
    	return Tools.getProperties(fileName);
    }
}